package com.smh.hmdianping.interceptor;

import cn.hutool.core.bean.BeanUtil;
import com.smh.hmdianping.constant.UserConstant;
import com.smh.hmdianping.pojo.User;
import com.smh.hmdianping.util.UserLocalThread;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author shiminghui
 * @date 2025/3/27 15:35
 * @description: TODO
 */
@Component
public class LoginInterceptor implements HandlerInterceptor, Ordered {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        User user = (User)request.getSession().getAttribute("user");
        String token = request.getHeader("token");
        // 从redis中读取用户信息
        Map entries = redisTemplate.opsForHash().entries(UserConstant.USER_PREFIX + token);

        if (entries.isEmpty()) {
            // 未登录
            response.setStatus(401);
            return false;
        }
        User user = BeanUtil.mapToBean(entries, User.class, true);
        UserLocalThread.User user1 = new UserLocalThread.User();
        BeanUtil.copyProperties(user, user1);
        UserLocalThread.setUser(user1);
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
